package com.awesome.spring.service.impl;

import com.alibaba.fastjson.JSON;
import com.awesome.spring.bean.Order;
import com.awesome.spring.feign.AccountFeign;
import com.awesome.spring.mapper.OrderMapper;
import com.awesome.spring.service.OrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;

/**
 * OrderServiceImpl
 *
 * @author alex
 * @date 2022/07/07
 */

@Slf4j
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private AccountFeign accountFeign;


    @Autowired
    private RocketMQTemplate rocketMQTemplate;


    @Override
    public void create(String userId, int money, boolean rollback) {
        // 1. 生成订单对象 （此时不保存）
        String orderCode = UUID.randomUUID().toString();

        Order order = new Order();
        order.setCode(orderCode);
        order.setCount(1);
        order.setUserId(userId);
        order.setMoney(money);


        // 2. 发送事务信息（消息暂不投递）

        Message message = MessageBuilder.withPayload(JSON.toJSONString(order)).setHeader("order", orderCode).build();

        TransactionSendResult result=rocketMQTemplate.sendMessageInTransaction(
                "tx-order-topic", // 主题
                message, // 消息体
                order // 事务参数（会传给监听器）
                );

        log.info("事务消息发送状态: {}", result.getLocalTransactionState());

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveInTransaction(Order order) {
        // 1. 保存订单
        this.save(order);
//        int a = 1/0 ; // 模拟异常
    }
}
